package com.event.management.backend.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import com.event.management.backend.dto.TicketDTO;
import com.event.management.backend.dto.TicketStatsDTO;
import com.event.management.backend.service.TicketService;
import com.event.management.backend.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 票种控制器
 * 提供票种的增删改查和统计功能
 */
@Api(tags = "票种管理接口", description = "提供票种的增删改查和统计功能")
@RestController
@RequestMapping("/api")
public class TicketController {
    
    @Autowired
    private TicketService ticketService;
    
    /**
     * 获取票种列表
     * @param eventId 活动ID
     * @return 票种列表
     */
    @ApiOperation(value = "获取票种列表", notes = "根据活动ID获取该活动下的所有票种列表，需要管理员或活动创建者权限")
    @GetMapping("/events/{eventId}/tickets")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<List<TicketDTO>> getTicketList(
            @ApiParam(value = "活动ID", required = true, example = "1") @PathVariable Long eventId) {
        if (eventId == null || eventId <= 0) {
            return Result.validateFailed("活动ID不合法");
        }
        
        List<TicketDTO> ticketList = ticketService.getTicketsByEventId(eventId);
        return Result.success(ticketList);
    }
    
    /**
     * 添加票种
     * @param ticketDTO 票种信息
     * @return 新增的票种信息
     */
    @ApiOperation(value = "添加票种", notes = "添加新票种，需要管理员或活动创建者权限。票种信息包括名称、描述、价格、库存等")
    @PostMapping("/tickets")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<TicketDTO> addTicket(@Validated @RequestBody TicketDTO ticketDTO) {
        try {
            // 检查是否有权限管理此活动的票种
            if (!ticketService.checkTicketManagePermission(ticketDTO.getEventId())) {
                return Result.error(403, "您没有权限管理此活动的票种");
            }
            
            Long ticketId = ticketService.addTicket(ticketDTO);
            
            // 查询新增的票种信息并返回
            TicketDTO newTicket = ticketService.getTicketById(ticketId);
            return Result.success(newTicket, "添加票种成功");
        } catch (Exception e) {
            return Result.error(500, "添加票种失败：" + e.getMessage());
        }
    }
    
    /**
     * 修改票种
     * @param eventId 活动ID
     * @param ticketId 票种ID
     * @param ticketDTO 票种信息
     * @return 修改结果
     */
    @ApiOperation(value = "修改票种", notes = "修改票种信息，需要管理员或活动创建者权限。可修改票种名称、描述、价格、库存等，但不能修改已售数量")
    @PutMapping("/events/{eventId}/tickets/{ticketId}")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<Boolean> updateTicket(
            @ApiParam(value = "活动ID", required = true, example = "1") @PathVariable Long eventId,
            @ApiParam(value = "票种ID", required = true, example = "1") @PathVariable Long ticketId,
            @Validated @RequestBody TicketDTO ticketDTO) {
        if (eventId == null || eventId <= 0) {
            return Result.validateFailed("活动ID不合法");
        }
        
        if (ticketId == null || ticketId <= 0) {
            return Result.validateFailed("票种ID不合法");
        }
        
        try {
            // 获取已存在的票种信息，用于权限检查
            TicketDTO existingTicket = ticketService.getTicketById(ticketId);
            if (existingTicket == null) {
                return Result.error(404, "票种不存在或已被删除");
            }
            
            // 验证票种是否属于指定活动
            if (!existingTicket.getEventId().equals(eventId)) {
                return Result.error(400, "票种不属于指定活动");
            }
            
            // 检查是否有权限管理此活动的票种
            if (!ticketService.checkTicketManagePermission(eventId)) {
                return Result.error(403, "您没有权限管理此活动的票种");
            }
            
            // 确保更新时使用正确的活动ID
            ticketDTO.setEventId(eventId);
            
            boolean success = ticketService.updateTicket(ticketId, ticketDTO);
            if (!success) {
                return Result.error(404, "票种不存在或已被删除");
            }
            return Result.success(success, "更新票种成功");
        } catch (Exception e) {
            return Result.error(500, "更新票种失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除票种（逻辑删除）
     * @param id 票种ID
     * @return 删除结果
     */
    @ApiOperation(value = "删除票种", notes = "逻辑删除票种，需要管理员或活动创建者权限。删除后票种不会在列表中显示，但数据仍保留在数据库中")
    @DeleteMapping("/tickets/{id}")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<Boolean> deleteTicket(
            @ApiParam(value = "票种ID", required = true, example = "1") @PathVariable Long id) {
        if (id == null || id <= 0) {
            return Result.validateFailed("票种ID不合法");
        }
        
        try {
            // 获取票种信息，用于权限检查
            TicketDTO existingTicket = ticketService.getTicketById(id);
            if (existingTicket == null) {
                return Result.error(404, "票种不存在或已被删除");
            }
            
            // 检查是否有权限管理此活动的票种
            if (!ticketService.checkTicketManagePermission(existingTicket.getEventId())) {
                return Result.error(403, "您没有权限管理此活动的票种");
            }
            
            boolean success = ticketService.deleteTicket(id);
            return Result.success(success, "删除票种成功");
        } catch (Exception e) {
            return Result.error(500, "删除票种失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取票种销售统计数据
     * @param id 票种ID
     * @return 销售统计数据
     */
    @ApiOperation(value = "获取票种销售统计", notes = "获取票种销售数据统计信息，包括已售数量、剩余数量、销售总额和销售率，需要管理员或活动创建者权限")
    @GetMapping("/tickets/{id}/stats")
    @SaCheckRole(value = {"admin", "organizer"}, mode = SaMode.OR)
    public Result<TicketStatsDTO> getTicketStats(
            @ApiParam(value = "票种ID", required = true, example = "1") @PathVariable Long id) {
        if (id == null || id <= 0) {
            return Result.validateFailed("票种ID不合法");
        }
        
        try {
            TicketStatsDTO stats = ticketService.getTicketStats(id);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error(500, "获取票种销售统计失败：" + e.getMessage());
        }
    }
} 